'''
中华一心一意重大疾病保险计划
'''

import sys
sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json
from common.helper import Helper
from threading import Thread
from pprint import pprint

class Spider(object):
    def __init__(self):

        self.mysql = MysqlClient()
        self.name = "中华一心一意重大疾病保险计划"

    # 生成产品数据
    def genProductInfo(self):

        plan = {
            # 不吸烟人群 1-18
            "planA": {
                # 年龄段
                "year": [str(i) for i in range(1, 19)],
                # 性别 男 M 女 F
                "gender": ["M", "F"],
                # 是否吸烟
                "smokeFlag": ["0"],
                # 保险期间
                "expire": ["终身"],
                # 缴费期间
                "paytime": ["10", "15", "20", "30"],
                # 理赔金额
                "money": ["5", "10", "20", "30", "40", "50"]

            },
            # 吸烟人群 19 - 35 缴费期间 10 - 30
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(19, 36)],
                # 性别 男 M 女 F
                "gender": ["M", "F"],
                # 是否吸烟 0 不吸烟 1 吸烟
                "smokeFlag": ["0", "1"],
                # 保险期间
                "expire": ["终身"],
                # 缴费期间
                "paytime": ["10", "15", "20", "30"],
                # 理赔金额
                "money": ["5", "10", "20", "30", "40", "50"]

            },
            # 吸烟人群 36 - 45 缴费期间 10 - 20
            "planC": {
                # 年龄段
                "year": [str(i) for i in range(36, 46)],
                # 性别 男 M 女 F
                "gender": ["M", "F"],
                # 是否吸烟 0 不吸烟 1 吸烟
                "smokeFlag": ["0", "1"],
                # 保险期间
                "expire": ["终身"],
                # 缴费期间
                "paytime": ["10", "15", "20"],
                # 理赔金额
                "money": ["5", "10", "20", "30", "40", "50"]
            },
            # 吸烟人群 46 - 55 缴费 10
            "planD": {
                # 年龄段
                "year": [str(i) for i in range(46, 55)],
                # 性别 男 M 女 F
                "gender": ["M", "F"],
                # 是否吸烟 0 不吸烟 1 吸烟
                "smokeFlag": ["0", "1"],
                # 保险期间
                "expire": ["终身"],
                # 缴费期间
                "paytime": ["10"],
                # 理赔金额
                "money": ["5", "10", "20", "30", "40", "50"]

            }
        }

        for k in plan:

            for v in product(plan[k]["year"], plan[k]["gender"], plan[k]["smokeFlag"], plan[k]["expire"],
                             plan[k]["paytime"], plan[k]["money"]):
                # 写入数据库
                print(domain[self.name]["insert_sql"].format(v[0], v[1], v[2], v[3], v[4], v[5]))
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(v[0], v[1], v[2], v[3], v[4], v[5]))
                self.mysql._conn.commit()
                print("%s产品信息写入数据库成功" % self.name)

    # 执行爬虫
    def requestJson(self, dt=None, mysql=None,null=None):

        data = {
            "insuredEntity": {"sex": dt["gender"], "birthday": "{year}-12-20".format(year=str(2019 - int(dt["year"]))),
                              "smokeFlag": dt["smokeFlag"]},
            "riskFactsList": [{"name": "factor_F0019E_019E20_insuYear", "key": "insuYear", "value": "105"},
                              {"name": "factor_F0019E_019E20_payIntv", "key": "payIntv", "value": "12"},
                              {"name": "factor_F0019E_019E20_payEndYear", "key": "payEndYear", "value": dt["paytime"]},
                              {"name": "factor_F0019E_019E20_amnt", "key": "amnt", "value":dt["money"] + "0000"},
                              {"name": "factor_F0019E_019E20_prem", "key": "prem", "value": "1428.00"}],
            "productInfo": {"id": "297037078742381", "productCode": "F0019E", "name": "中华怡馨重大疾病保险",
                            "serverTime": "2019-12-20", "riskList": [
                    {"id": "2970370787423766", "riskCode": "F0019E", "nameCn": "中华怡馨重大疾病保险", "mainCovRiderFlg": "M",
                     "mult": null, "dutyList": [
                        {"dutyId": "29703707874237266", "riskCode": "F0019E", "dutyCode": "019E20",
                         "dutyName": "中华怡馨重大疾病责任", "choflg": "M", "vpu": "1000", "calmode": null, "mult": null,
                         "rate": null, "extProperties": null, "riskInputFactors": [
                            {"key": "insuYear", "name": "保险期间", "comp": "SingleComboBox", "val": "105",
                             "nullable": "true", "required": "false", "maxVal": "0", "minVal": "0", "desc": null,
                             "dic": [{"v": "终身", "k": "105"}], "readonly": "true", "disabled": "true",
                             "dataType": "P", "mod": "1", "dutyCode": "019E20", "ctrlType": "P", "effacted": null},
                            {"key": "payIntv", "name": "交费间隔", "comp": "SingleComboBox", "val": "12",
                             "nullable": "true", "required": "false", "maxVal": "0", "minVal": "0",
                             "desc": "空白=表示有多项选择，需要从界面传入,有固定值=表示有唯一的交费间隔,=1=不定期缴费,0=趸缴1=月缴,3=季缴6=半年缴,12=年缴",
                             "dic": [{"v": "年交", "k": "12"}], "readonly": "false", "disabled": "false",
                             "dataType": "P", "mod": "1", "dutyCode": "019E20", "ctrlType": "P", "effacted": null},
                            {"key": "payEndYear", "name": "交费期间", "comp": "SingleComboBox", "val": "10",
                             "nullable": "false", "required": "true", "maxVal": "0", "minVal": "0", "desc": null,
                             "dic": [{"v": "10年", "k": "10"}, {"v": "15年", "k": "15"}, {"v": "20年", "k": "20"},
                                     {"v": "30年", "k": "30"}], "readonly": "false", "disabled": "false",
                             "dataType": "P", "mod": "1", "dutyCode": "019E20", "ctrlType": "P",
                             "effacted": "insuredPeople_birthday"},
                            {"key": "amnt", "name": "保额", "comp": "SelectList", "val": dt["money"] + "0000",
                             "nullable": "true",
                             "required": "false", "maxVal": "0", "minVal": "0", "desc": null,
                             "dic": [{"v": "5万", "k": "50000"}, {"v": "10万", "k": "100000"},
                                     {"v": "20万", "k": "200000"}, {"v": "30万", "k": "300000"},
                                     {"v": "40万", "k": "400000"}, {"v": "50万", "k": "500000"}], "readonly": "false",
                             "disabled": "false", "dataType": "P", "mod": "1", "dutyCode": "019E20",
                             "ctrlType": "P", "effacted": null}]}],
                     "extProperties": [{"field": "RnewFlag", "name": "自动续保标记（续保次数）", "val": "N"}]}]},
            "freeRiskFlag": "N", "rnewFlag": "Y"}

        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=json.dumps(data))

        pprint( r.json( ))

        if r.status_code == 200 and r.json()["message"] == "试算成功":

            price = Helper.decimalParse(r.json()["data"]["ssResult"]["insurances"][0]["businessObj"]["policyPrem"])

            data = {

                "name":self.name,
                "id":dt["id"],
                "price":price
            }

            mysql.updatePrice( data )

        else:

            data = {

                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            mysql.randTask(data)

    def main(self,mysql):

        while True:

            # 随机领取一条数据
            dt = mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

            # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            mysql.updateTask(data)

            self.requestJson(dt,mysql)

    def startProcess(self):

        threads = []

        for i in range(5):

            mysql = MysqlClient()

            t = Thread( target=self.main,args=(mysql,))

            t.start()

            threads.append( t )


        for t in threads:

            t.join()


if __name__ == '__main__':
    s = Spider()
    s.startProcess()
